#!/usr/bin/env python3
"""
启动Web演示服务器 - 解决CORS问题
"""

import http.server
import socketserver
import webbrowser
import threading
import time
from pathlib import Path

class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
    """支持CORS的HTTP请求处理器"""
    
    def end_headers(self):
        # 添加CORS头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        super().end_headers()
    
    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

def start_web_server(port=8080):
    """启动Web服务器"""
    try:
        # 切换到项目根目录
        project_root = Path(__file__).parent.parent
        import os
        os.chdir(project_root)
        
        with socketserver.TCPServer(("", port), CORSRequestHandler) as httpd:
            print(f"✅ Web服务器启动成功！")
            print(f"📍 服务地址: http://localhost:{port}")
            print(f"🌐 演示页面: http://localhost:{port}/demo/web/simple_demo.html")
            print(f"\n按 Ctrl+C 停止服务器")
            
            # 打开浏览器
            threading.Timer(1.0, lambda: webbrowser.open(f'http://localhost:{port}/demo/web/simple_demo.html')).start()
            
            httpd.serve_forever()
    except OSError as e:
        if e.errno == 10048:  # 端口被占用
            print(f"❌ 端口 {port} 已被占用，请尝试其他端口")
            print(f"提示: 运行 'python demo/start_web_demo.py --port 8081'")
        else:
            print(f"❌ 启动失败: {e}")
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")

if __name__ == "__main__":
    import sys
    
    port = 8080
    if '--port' in sys.argv:
        try:
            port = int(sys.argv[sys.argv.index('--port') + 1])
        except (IndexError, ValueError):
            print("❌ 端口号无效")
            sys.exit(1)
    
    print("=" * 60)
    print("🌐 离线语言播放系统 - Web演示服务器")
    print("=" * 60)
    print("\n注意事项:")
    print("1. 此服务器用于解决浏览器CORS限制")
    print("2. 后端API服务需要在 http://localhost:8000 运行")
    print("3. 如果后端未运行，请先执行: python demo/start_demo.py")
    print("\n" + "=" * 60 + "\n")
    
    start_web_server(port)